<!DOCTYPE html>
<!--
  The MIT License (MIT)

  Copyright (c) 2017 Tarek Sherif

  Permission is hereby granted, free of charge, to any person obtaining a copy of
  this software and associated documentation files (the "Software"), to deal in
  the Software without restriction, including without limitation the rights to
  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  the Software, and to permit persons to whom the Software is furnished to do so,
  subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-->
<html>
<head>
    <title>PicoGL.js: Picking</title>
    <meta charset="utf-8">
    <script src="utils/gl-matrix.js"></script>
    <script src="../build/picogl.js"></script>
    <script src="utils/utils.js"></script>
    <link rel="stylesheet" href="../site/css/picogl-example.css"> 
</head>
<body>
    <div id="example-title">
        PicoGL.js Example: Picking
        <div>
            <a href="https://github.com/tsherif/picogl.js/blob/master/examples/picking.html">Source code</a>
        </div>
    </div>
    <canvas id="gl-canvas"></canvas> 
    <script id="picking-vs" type="x-vertex-shader">
        #version 300 es

        layout(location=0) in vec4 aPosition;
        
        uniform mat4 uMVP;

        void main() {
            gl_Position = uMVP * aPosition;
        }
    </script>
    <script id="picking-fs" type="x-fragment-shader">
        #version 300 es
        precision highp float;

        uniform vec3 uPickColor;

        out vec4 fragColor;
        void main() {
            fragColor = vec4(uPickColor, 1.0);
        }
    </script>
    <script id="main-vs" type="x-vertex-shader">
        #version 300 es
        
        layout(std140, column_major) uniform;

        layout(location=0) in vec4 aPosition;
        layout(location=1) in vec3 aNormal;
        layout(location=2) in vec2 aTexCoord;

        uniform FrameUniforms {
            mat4 uMVP;
            mat4 uModelMatrix;
            vec4 uHighlightColor;
        };
        
        out vec3 vPosition;
        out vec3 vNormal;
        out vec2 vTexCoord;
        void main() {
            gl_Position = uMVP * aPosition;

            vPosition = vec3(uModelMatrix * aPosition);
            vNormal = vec3(uModelMatrix * vec4(aNormal, 0.0));
            vTexCoord = aTexCoord;
        }
    </script>
    <script id="main-fs" type="x-fragment-shader">
        #version 300 es
        precision highp float;

        layout(std140, column_major) uniform;

        uniform SceneUniforms {
            vec4 uLightPosition;
            vec4 uEyePosition;
        };

        uniform FrameUniforms {
            mat4 uMVP;
            mat4 uModelMatrix;
            vec4 uHighlightColor;
        };

        uniform sampler2D uTextureMap;

        in vec3 vPosition;
        in vec3 vNormal;
        in vec2 vTexCoord;

        out vec4 fragColor;
        void main() {
            vec4 baseColor = texture(uTextureMap, vTexCoord);

            vec3 normal = normalize(vNormal);
            vec3 eyeDirection = normalize(uEyePosition.xyz - vPosition);
            vec3 lightDirection = normalize(uLightPosition.xyz - vPosition);
            vec3 reflectionDirection = reflect(-lightDirection, normal);
            float nDotL = max(dot(lightDirection, normal), 0.0);
            float diffuse = nDotL;
            float ambient = 0.1;
            float specular = pow(max(dot(reflectionDirection, eyeDirection), 0.0), 20.0);

            fragColor = vec4(uHighlightColor.rgb * (ambient + diffuse + specular) * baseColor.rgb, baseColor.a);
        }
    </script>
    <script type="text/javascript">
        utils.addTimerElement();

        var canvas = document.getElementById("gl-canvas");

        if (!utils.testWebGL2()) {
            console.error("WebGL 2 not available");
            document.body.innerHTML = "This example requires WebGL 2 which is unavailable on this system."
        }

        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        
        var app = PicoGL.createApp(canvas)
        .clearColor(0.0, 0.0, 0.0, 1.0)
        .depthTest()
        .cullBackfaces();

        var timer = app.createTimer();

        // SET UP PICKING PROGRAM
        var pickingVsSource = document.getElementById("picking-vs").text.trim();
        var pickingFsSource = document.getElementById("picking-fs").text.trim();
        var pickingProgram = app.createProgram(pickingVsSource, pickingFsSource);

        var pickColorTarget = app.createTexture2D(app.width, app.height);
        var pickDepthTarget = app.createRenderbuffer(app.width, app.height, PicoGL.DEPTH_COMPONENT16);

        var pickingBuffer = app.createFramebuffer().colorTarget(0, pickColorTarget).depthTarget(pickDepthTarget);

        // SET UP MAIN PROGRAM
        var vsSource = document.getElementById("main-vs").text.trim();
        var fsSource = document.getElementById("main-fs").text.trim();
        var mainProgram = app.createProgram(vsSource, fsSource);

        // GEOMETRY
        var box = utils.createBox({dimensions: [1.0, 1.0, 1.0]})
        var positions = app.createVertexBuffer(PicoGL.FLOAT, 3, box.positions);
        var uv = app.createVertexBuffer(PicoGL.FLOAT, 2, box.uvs);
        var normals = app.createVertexBuffer(PicoGL.FLOAT, 3, box.normals);

        var boxArray = app.createVertexArray()
        .vertexAttributeBuffer(0, positions)
        .vertexAttributeBuffer(1, normals)
        .vertexAttributeBuffer(2, uv);

        // UNIFORMS
        var projMatrix = mat4.create();
        mat4.perspective(projMatrix, Math.PI / 2, canvas.width / canvas.height, 0.1, 2.0);

        var viewMatrix = mat4.create();
        var eyePosition = vec3.fromValues(1, 1, 1);
        mat4.lookAt(viewMatrix, eyePosition, vec3.fromValues(0, 0, 0), vec3.fromValues(0, 1, 0));

        var viewProjMatrix = mat4.create();
        mat4.multiply(viewProjMatrix, projMatrix, viewMatrix);

        var lightPosition = vec3.fromValues(1, 1, 0.5);  

        var highlightColor = vec3.fromValues(1.5, 1.5, 0.5);
        var unhighlightColor = vec3.fromValues(1.0, 1.0, 1.0);

        // UNIFORM BUFFER
        var sceneUniforms = app.createUniformBuffer([
            PicoGL.FLOAT_VEC4,
            PicoGL.FLOAT_VEC4
        ]).set(0, lightPosition)
        .set(1, eyePosition)
        .update();

        window.onresize = function() {
            app.resize(window.innerWidth, window.innerHeight);
            pickingBuffer.resize();

            mat4.perspective(projMatrix, Math.PI / 2, app.width / app.height, 0.1, 10.0);
            mat4.multiply(viewProjMatrix, projMatrix, viewMatrix);
        };

        // OBJECT DESCRIPTIONS
        var boxes = [
            {
                translate: [0, 0, 0],
                rotate: [0, 0, 0],
                scale: [1, 1, 1],
                mvpMatrix: mat4.create(),
                modelMatrix: mat4.create(),
                pickColor: vec3.fromValues(1.0, 0.0, 0.0),
                frameUniforms: app.createUniformBuffer([
                    PicoGL.FLOAT_MAT4,
                    PicoGL.FLOAT_MAT4,
                    PicoGL.FLOAT_VEC4
                ]).set(2, unhighlightColor),
                mainDrawCall: null,
                pickingDrawCall: null
            },
            {
                translate: [0.8, 0.8, 0.4],
                rotate: [0, 0, Math.PI / 6],
                scale: [0.1, 0.1, 0.1],
                mvpMatrix: mat4.create(),
                modelMatrix: mat4.create(),
                pickColor: vec3.fromValues(0.0, 1.0, 0.0),
                frameUniforms: app.createUniformBuffer([
                    PicoGL.FLOAT_MAT4,
                    PicoGL.FLOAT_MAT4,
                    PicoGL.FLOAT_VEC4
                ]).set(2, unhighlightColor),
                mainDrawCall: null,
                pickingDrawCall: null
            }
        ];

        
        utils.loadImages(["img/webgl-logo.png"], function(images) {
            // CREATE TEXTURE
            var texture = app.createTexture2D(images[0], { flipY: true });

            for (var i = 0, len = boxes.length; i < len; ++i) {
                boxes[i].pickingDrawCall = app.createDrawCall(pickingProgram, boxArray)
                .uniform("uPickColor", boxes[i].pickColor);

                boxes[i].mainDrawCall = app.createDrawCall(mainProgram, boxArray)
                .uniformBlock("SceneUniforms", sceneUniforms)
                .uniformBlock("FrameUniforms", boxes[i].frameUniforms)
                .texture("uTextureMap", texture);
            }

            // MOUSE HANDLER FOR PICKING
            var mouseX = 0;
            var mouseY = 0;
            var picked = false;
            var pickedColor = new Uint8Array(4);

            window.addEventListener("mouseup", function(event) {
                mouseX = event.clientX;
                mouseY = event.clientY;
                picked = true;
            });

            function draw() {
                if (timer.ready()) {
                    utils.updateTimerElement(timer.cpuTime, timer.gpuTime);
                }


                timer.start();

                for (var i = 0, len = boxes.length; i < len; ++i) {
                    boxes[i].rotate[0] += 0.01;
                    boxes[i].rotate[1] += 0.02;

                    utils.xformMatrix(boxes[i].modelMatrix, boxes[i].translate, boxes[i].rotate, boxes[i].scale);
                    mat4.multiply(boxes[i].mvpMatrix, viewProjMatrix, boxes[i].modelMatrix);
                    
                    boxes[i].pickingDrawCall.uniform("uMVP", boxes[i].mvpMatrix);
                    
                    boxes[i].frameUniforms.set(0, boxes[i].mvpMatrix)
                    .set(1, boxes[i].modelMatrix);
                }

                if (picked) {
                    // DRAW TO PICKING BUFFER
                    app.drawFramebuffer(pickingBuffer).clear();

                    for (var i = 0, len = boxes.length; i < len; ++i) {
                        boxes[i].pickingDrawCall.draw();
                    }

                    app.defaultDrawFramebuffer()
                    .readFramebuffer(pickingBuffer)
                    .readPixel(mouseX, canvas.height - mouseY, pickedColor);
                    
                    if (pickedColor[0] === 255) {
                        boxes[0].frameUniforms.set(2, highlightColor);
                    } else {
                        boxes[0].frameUniforms.set(2, unhighlightColor);
                    }

                    if (pickedColor[1] === 255) {
                        boxes[1].frameUniforms.set(2, highlightColor);
                    } else {
                        boxes[1].frameUniforms.set(2, unhighlightColor);
                    }

                    picked = false;
                }

                boxes[0].frameUniforms.update();
                boxes[1].frameUniforms.update();

                // MAIN DRAW
                app.clear();
                
                for (var i = 0, len = boxes.length; i < len; ++i) {
                    boxes[i].mainDrawCall.draw();
                }

                timer.end();

                requestAnimationFrame(draw);
            }

            requestAnimationFrame(draw);
            
        });

    </script>
    <a href="https://github.com/tsherif/picogl.js" id="github-ribbon"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/365986a132ccd6a44c23a9169022c0b5c890c387/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f7265645f6161303030302e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png"></a>
    <script src="../site/js/iframe.js"></script>
</body>
</html>
